<?php
class ControllerAffiliateForgotten extends FrontController {

	public function index() {
		if ($this->affiliate->isLogged()) {
			$this->redirect(US('affiliate/account'));
		}
		
		$this->document->setTitle($this->_['heading_title']);
		
		M('affiliate/affiliate');

		if ($this->request->isPost() && $this->validate()) {
			$this->language->load('mail/forgotten');

			$password = substr(md5(mt_rand()), 0, 10);

			$this->model_affiliate_affiliate->editPassword($this->request->post['email'], $password);

			$subject = sprintf($this->_['text_subject'], C('config_name'));

			$message  = sprintf($this->_['text_greeting'], C('config_name')) . "\n\n";
			$message .= $this->_['text_password'] . "\n\n";
			$message .= $password;

			$mail = new Mail();
			$mail->protocol = C('config_mail_protocol');
			$mail->parameter = C('config_mail_parameter');
			$mail->hostname = C('config_smtp_host');
			$mail->username = C('config_smtp_username');
			$mail->password = C('config_smtp_password');
			$mail->port = C('config_smtp_port');
			$mail->timeout = C('config_smtp_timeout');
			$mail->setTo($this->request->post['email']);
			$mail->setFrom(C('config_email'));
			$mail->setSender(C('config_name'));
			$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
			$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
			$mail->send();

			$this->session->set_flashdata('success', $this->_['text_success']);

			$this->redirect(U('affiliate/login', '', 'SSL'));
		}
		
		$this->document->addScript('static/javascript/jquery/jquery.validate.js');
		
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->_['text_account'],
			'href'      => US('affiliate/account'),
        	'separator' => $this->_['text_separator']
      	);

      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->_['text_forgotten'],
			'href'      => US('affiliate/forgotten'),
        	'separator' => $this->_['text_separator']
      	);

		$this->display('affiliate/forgotten.tpl');
	}

	protected function validate() {
		if (!isset($this->request->post['email'])
			|| !$this->model_affiliate_affiliate->getTotalAffiliatesByEmail($this->request->post['email'])) {
			$this->setMessage('error_warning', $this->_['error_email']);
			return false;
		}

		return true;
	}
}
?>